package com.ustarlink.live;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.VideoView;

import com.ustarlink.live.fragment.EPGFragment;
import com.ustarlink.live.fragment.VideoViewFragment;
import com.ustarlink.live.net.EPGDownloadTask;

public class MainActivity extends Activity implements EPGFragment.OnChannelListItemSelectedListener{
    public static final String TAG = "MainActivity";
 //   private ChannelsAdapter mAdapter;
    private ListView channelList;
    private VideoView videoView;
    private String url;
    private FragmentManager manager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        VideoViewFragment videoViewFragment = null;
        manager = getFragmentManager();
        if (savedInstanceState != null){
            /** 启动VideoViewFragment **/
            videoViewFragment =(VideoViewFragment) manager.findFragmentByTag(VideoViewFragment.TAG);
        }
        if (videoViewFragment == null) {

            manager.beginTransaction()
                    .add(R.id.container, new VideoViewFragment(), VideoViewFragment.TAG).commit();
        }

        if(isNetworkAvailable()){
            Log.i(TAG, "starting download Task");
            EPGDownloadTask download = new EPGDownloadTask(this);
            download.execute();
        }
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }


    @Override
    public void onChannelListItemSelected(String url) {
        FragmentManager manager = getFragmentManager();
        VideoViewFragment videoViewFragment =
                (VideoViewFragment) manager.findFragmentByTag(MainActivity.TAG);
        videoViewFragment.getUrlFromEPG(url);

    }


}